/*
 * @Author: liuYang codkly@gmail.com
 * @Date: 2022-10-26 22:55:19
 * @LastEditors: liuYang codkly@gmail.com
 * @LastEditTime: 2022-11-07 10:31:46
 * @FilePath: \coding\blog\blog_server\src\common\utils.js
 * @Description: func
 * 暂无备注
 */

const { baseUrl } = require("../config");
const imgBaseUrl = "file/imgs/";

const nodemailer = require("nodemailer");
let jwt = require("jsonwebtoken");
/**
 *
 * @param {*} from 发件人邮箱
 * @param {*} aliasName 发件人
 * @param {*} tos 收件人邮箱
 * @param {*} subject 主题
 * @param {*} msg 正文
 */
// 参数：发件人，收件人，主题，正文（支持html格式）
function sendMail(from, aliasName, tos, subject, msg) {
  const smtpTransport = nodemailer.createTransport({
    host: "smtp.qq.com",
    secureConnection: true, // 使用了 SSL
    secure: true,
    port: 465, //SMTP 端口
    auth: {
      user: from, //发送邮件的账号
      pass: "eefsnbicbryhbjab", //smtp授权码
    },
  });
  console.log("===================>");
  smtpTransport.sendMail(
    {
      from: aliasName + " " + "<" + from + ">",
      to: tos,
      subject: subject,
      html: msg,
    },
    function (err, res) {
      console.log("res: ", res);
      if (err) {
        console.log("error: ", err);
      }
    }
  );
}
// 通过token 获取userid
function getUserId(ctx) {
  let token = ctx.request.headers["authorization"];
  try {
    if (token) {
      const tokenItem = jwt.verify(token.split("Bearer ")[1], "itliuyang");
      if (tokenItem) {
        return tokenItem.userid;
      }
    }
  } catch (error) {
    ctx.fail(0, error);
  }

  return "";
}
/**
 * @description: 获取完整图片地址
 * @param {*} path
 * @return {*}
 */
function getImgUrl(path) {
  return baseUrl + imgBaseUrl + path;
}

const utils = {
  sendMail: sendMail,
  getUserId: getUserId,
  getImgUrl:getImgUrl
};

module.exports = utils;
